package chapter16;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.border.TitledBorder;

public class LoanCalculator extends JFrame{
	private JTextField jtfAnnualInterestRate = new JTextField();
	private JTextField jtfNumberOfYears = new JTextField();
	private JTextField jtfLoanAmount = new JTextField();
	private JTextField jtfMonthlyPayment = new JTextField();
	private JTextField jtfTotalPayment = new JTextField();
	
	private JButton jbtComputeLoan = new JButton("Compute Payment");
	
	public LoanCalculator(){
		JPanel p1 = new JPanel(new GridLayout(5, 2));
		p1.add(new Label("Annual Interest Rate"));
		p1.add(jtfAnnualInterestRate);
		
		p1.add(new Label("Number of Years"));
		p1.add(jtfNumberOfYears);
		
		p1.add(new Label("Loan Amount"));
		p1.add(jtfLoanAmount);
		
		p1.add(new Label("Monthly Payment"));
		p1.add(jtfMonthlyPayment);
		
		p1.add(new Label("Total Payment"));
		p1.add(jtfTotalPayment);
		
		p1.setBorder(new TitledBorder("Enter loan amount, interest rate, and year"));
		
	
		JPanel p2 = new JPanel(new FlowLayout(FlowLayout.RIGHT));
		p2.add(jbtComputeLoan);
		
		
		add(p1, BorderLayout.CENTER);
		add(p2, BorderLayout.SOUTH);
		
		jbtComputeLoan.addActionListener(new ButtonListener());
		
	}
	
	private class ButtonListener implements ActionListener{
		public void actionPerformed(ActionEvent e){
			double interest = Double.parseDouble(jtfAnnualInterestRate.getText());
			int year = Integer.parseInt(jtfNumberOfYears.getText());
			double loanAmount = Double.parseDouble(jtfLoanAmount.getText());
			
			double monthlyPayment = getMOnthlyPayment(interest, year, loanAmount);
			jtfMonthlyPayment.setText(String.format("%.2f", monthlyPayment));
			jtfTotalPayment.setText(String.format("%.2f", getTotalPayment(monthlyPayment, year)));
		}
	}
	
	private double getMOnthlyPayment(double interest, int years, double loanAmount){
		double monthlyInterestRate = interest / 1200;
		double monthlyPayment = loanAmount * monthlyInterestRate / (1- (Math.pow(1 / (1 + monthlyInterestRate), years * 12)));
		return monthlyPayment;
	}
	
	private double getTotalPayment(double monthlyPayment, int years){
		double totalPayment = monthlyPayment * years * 12;
		return totalPayment;
	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		LoanCalculator frame = new LoanCalculator();
		frame.pack();
		frame.setTitle("LoanCalculator");
		frame.setLocationRelativeTo(null);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.setVisible(true);
	}

}
